package com.leo.cloud.common.utils.docks;

import com.leo.cloud.common.utils.Constant;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 文件名：ExportDocx.java
 *
 * @create 2021-03-26 10:27
 * <p>
 */
public class ExportDocx {
    private static final String separator = File.separator;

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(8);
        map.put("tag1", "11111");
        map.put("tag2", "测试");
        map.put("tag3", "11名字1");
        map.put("tag4", "11名字1");
        createApplyPdf(map, Constant.fileRootpath+"export_template"+separator,"document.xml", "test.docx",
                Constant.fileRootpath+"export_out"+separator);
        //        convert();
        //        addTextMark("D:\\test\\test.pdf", "D:\\test\\test2.pdf");
    }

    public static String createApplyPdf(Map<String, Object> dataMap, String templateBasePath, String documentXmlName, String docxTempName,String outPath) throws Exception {
        ZipOutputStream zipout = null;//word输出流
        File tempPath = null;//docx格式的word文件路径
            File file= new File(outPath);
            if(!file.exists()){
                file.mkdirs();
            }
            //freemark根据模板生成内容xml
            //================================获取 document.xml 输入流================================
//            ByteArrayInputStream documentInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, documentXmlName, separator + "template" + separator + "downLoad" + separator);
            ByteArrayInputStream documentInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, documentXmlName, templateBasePath);
            //================================获取 document.xml 输入流================================
            //获取主模板docx
//            ClassPathResource resource = new ClassPathResource(System.getProperties( ).getProperty("user.dir")+separator + docxTempName);
//            File docxFile = resource.getFile( );
            File docxFile = new File(templateBasePath+docxTempName);
            ZipFile zipFile = new ZipFile(docxFile);
            Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries( );

            //输出word文件路径和名称
            String outFileName = docxTempName.substring(0, docxTempName.lastIndexOf("."))+"_"+System.currentTimeMillis()+".docx";
//            String outPutWordPath = System.getProperty("java.io.tmpdir").replaceAll(separator + "$", "") + separator + fileName;
            String outPutWordPath =outPath + outFileName;

            tempPath = new File(outPutWordPath);
            //如果输出目标文件夹不存在，则创建
            if (!tempPath.getParentFile( ).exists( )) {
                tempPath.mkdirs( );
            }
            //docx文件输出流
            zipout = new ZipOutputStream(new FileOutputStream(tempPath));
            //循环遍历主模板docx文件,替换掉主内容区，也就是上面获取的document.xml的内容
            //------------------覆盖文档------------------
            int len = -1;
            byte[] buffer = new byte[1024];
            while (zipEntrys.hasMoreElements( )) {
                ZipEntry next = zipEntrys.nextElement( );
                InputStream is = zipFile.getInputStream(next);
                if (next.toString( ).indexOf("media") < 0) {
                    zipout.putNextEntry(new ZipEntry(next.getName( )));
                    if ("word/document.xml".equals(next.getName( ))) {
                        //写入填充数据后的主数据信息
                        if (documentInput != null) {
                            while ((len = documentInput.read(buffer)) != -1) {
                                zipout.write(buffer, 0, len);
                            }
                            documentInput.close( );
                        }
                    } else {//不是主数据区的都用主模板的
                        while ((len = is.read(buffer)) != -1) {
                            zipout.write(buffer, 0, len);
                        }
                        is.close( );
                    }
                }
            }
            //------------------覆盖文档------------------
            zipout.close( );//关闭

            //----------------word转pdf--------------
//            return convertDocx2Pdf(outPath,outPutWordPath);

        try {
            if (zipout != null) {
                zipout.close( );
            }
        } catch (Exception ex) {
            ex.printStackTrace( );
        }
        return tempPath==null?"":tempPath.getAbsolutePath();
    }

}
